<template>
  <div class="tool-container max-w-8xl mx-auto px-4 pt-7 pb-16 sm:px-6 lg:px-4">
    <div class="breadcrumbs space-x-2 text-base flex flex-wrap items-center">
      <common-link path="/gpts"
        class="text-gray-1000 hover:text-purple-1200 go-home">
        {{$t('gpts_detail_allGPTs')}}
      </common-link>
      <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
        iconName='right_outlined'></svg-icon>
      <span class="text-gray-1400 text-base">
        {{$t('gpts_detail_GPTsToolName', {toolName:tool.name})}}
      </span>
    </div>
    <div class="mt-10 box pt-6 pb-5 px-6">
      <div class="md:flex md:items-center md:justify-between">
        <div class="sm:flex sm:items-center gap-5">
          <div class="flex tool-pic items-center justify-center skeleton-bg"
            ref="imgBox">
            <img class="w-full h-full flex-shrink-0 object-contain"
              :src="tool.img_url ? tool.img_url : 'https://cdn.toolify.ai/gpt-default.webp'"
              v-real-img-gpt="tool.img_url"
              @load='imgOnError'
              :alt="tool.name ? tool.name : 'Toolify'"
              loading="lazy" />
          </div>
          <h1 class="tool-name text-gray-1000 break-words font-bold">{{tool.name}}</h1>
        </div>
        <div class="mt-4 md:mt-0 md:ml-4">
          <min-share></min-share>
        </div>
      </div>

      <div class="mt-7 break-words">
        <p class="text-gray-1000 text-base leading-7">
          <span class="mr-3"
            v-if="hasRealVal(tool.official_website_link)"
            v-html="$t('gpts_detail_ByLink', {official_website_link: tool.official_website_link, author:tool.author ? tool.author:tool.official_website_link })"></span>
          <span class="mr-3"
            v-else-if="hasRealVal(tool.author)">{{$t('gpts_detail_By', {author:tool.author})}}</span>
          <span class="mr-3"
            v-else>{{$t('gpts_detail_By', {author: 'community builder'})}}</span>

          <span class="mr-3"
            v-if="hasRealVal(tool.num_conversations)">{{$t('gpts_detail_numberOofCalls', {num:$vReset(tool.num_conversations)})}}</span>
          <span class="mr-3"
            v-if="hasRealVal(tool.created_at)">{{$t('gpts_detail_createdAt', {date:$formattedDate(tool.created_at, fI18n, locale)})}}</span>
          <span v-if="hasRealVal(tool.gpt_updated_at)">{{$t('gpts_detail_updateddate', {updateddate:$formattedDate(tool.gpt_updated_at, fI18n, locale)})}}</span>
        </p>

        <div class="sm:flex items-start justify-center mt-3 gap-5">
          <div class="flex-1 sm:w-0 sm:min-h-11 sm:flex items-center">
            <p v-if="hasRealVal(tool.describe)"
              class="text-gray-1000 text-base leading-7">{{tool.describe}}</p>
          </div>

          <div class="flex-shrink-0 mt-5 sm:mt-0">
            <a class="flex-1 flex max-w-full sm:inline-flex mx-auto bg-blue-1300 justify-center radius-22 py-2 px-4 sm:px-6 hover:bg-blue-1500 focus:bg-blue-1600 to-view-btn"
              :href="tool.link"
              rel="nofollow"
              target="_blank">
              <span class="text-lg text-white whitespace-nowrap">{{$t('gpts_detail_useOnChatGPT', {toolName:tool.name})}}</span>
            </a>
          </div>
        </div>
      </div>

      <el-divider class="mt-6 mb-5"
        v-if="hasRealVal(tool.ai_content) && Array.isArray(tool.ai_content.categories) && tool.ai_content.categories.length > 0"></el-divider>

      <div class="flex items-start flex-wrap gap-x-3 gap-y-3"
        v-if="hasRealVal(tool.ai_content) && Array.isArray(tool.ai_content.categories) && tool.ai_content.categories.length > 0">
        <div class="text-base text-purple-1700 border border-purple-1500 bg-purple-1600 max-w-max truncate rounded-2xl t-label"
          v-for="(item, key) in tool.ai_content.categories"
          :key="key">{{item}}</div>
      </div>
    </div>

    <div class="border border-white px-6">
      <gpts-tool-detail-functions class="mt-14"
        :tool="tool"
        v-if="tool && tool.ai_content &&  Array.isArray(tool.ai_content.function) && tool.ai_content.function.length > 0"></gpts-tool-detail-functions>

      <gpts-tool-detail-text class="mt-12"
        :tool="tool"
        title="gpts_detail_whoIsSuitableToUse"
        :desc="tool.ai_content.synopsis"
        v-if="tool && tool.ai_content && tool.ai_content.synopsis"></gpts-tool-detail-text>

      <gpts-tool-detail-text class="mt-5"
        :tool="tool"
        title="gpts_detail_howDoIUse"
        :desc="tool.ai_content.quick_start"
        v-if="tool && tool.ai_content && tool.ai_content.quick_start"></gpts-tool-detail-text>

      <gpts-tool-detail-text class="mt-5"
        :tool="tool"
        title="gpts_detail_howToUse"
        :desc="tool.ai_content.how_to_use"
        v-if="tool && tool.ai_content && tool.ai_content.how_to_use"></gpts-tool-detail-text>

      <gpts-tool-detail-tags class="mt-20"
        :tool="tool"
        v-if="tool && tool.ai_content &&  Array.isArray(tool.ai_content.tags) && tool.ai_content.tags.length > 0"></gpts-tool-detail-tags>

      <gpts-tool-detail-faq class="mt-20"
        :tool="tool"
        :faq="tool.ai_content.faq"
        v-if="tool && tool.ai_content && Array.isArray(tool.ai_content.faq) && tool.ai_content.faq.length > 0">
      </gpts-tool-detail-faq>

      <h2 class="bar-title break-words mt-20"
        v-if="more_by_author && Array.isArray(more_by_author) && more_by_author.length > 0">
        <span class="text-gray-1000 font-bold text-26 leading-7 break-words w-full">
          {{$t('gpts_detail_moreBy',{author: tool.author})}}
        </span>
      </h2>
      <div class="tools grid gap-5 sm:grid-cols-2 lg:grid-cols-3 mt-7"
        v-if="more_by_author && Array.isArray(more_by_author) && more_by_author.length > 0">
        <gpts-tool v-for="(item, key) in more_by_author"
          :key="item.handle+'-'+key"
          :toolsData="item"></gpts-tool>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
export default {
  name: 'ToolPage',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error }) {
    if (process.server) {
    }
    try {
      let [toolsRes] = await Promise.all([
        await $axiosApi.chatgptsDetail(params.handle),
      ])

      let tool = {},
        more_by_author = []

      if (toolsRes.code === 200) {
        tool = toolsRes.data.chatgpts
        more_by_author = toolsRes.data.more_by_author
      } else {
        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message: app.i18n.t('error_401'),
            statusCode: toolsRes.code,
          })
        }
      }
      let description = app.i18n.t('gpts_detail_pageDesc', {
        toolName: tool.name,
        describe: tool.describe,
      })
      let title = app.i18n.t('gpts_detail_pageTitle', { toolName: tool.name })
      return { tool, more_by_author, title, description }
    } catch (err) {
      console.log(err)
    }
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val
      }
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,
      tool: {},
      more_by_author: [],

      cLoading: false,
    }
  },
  methods: {
    imgOnError() {
      this.$refs.imgBox.classList.remove('skeleton-bg')
    },
    async addOrCancleFavorites() {
      this.cLoading = true
      try {
        try {
          let res

          switch (this.tool.user_collected) {
            case 0:
              res = await this.$axiosApi.postFavoritesChatgpts({
                g_id: this.$route.params.handle,
              })
              break
            case 1:
              res = await this.$axiosApi.deleteFavoritesChatgpts({
                g_id: this.$route.params.handle,
              })
              break
            default:
              console.log('error')
          }

          this.cLoading = false
          if (res && res.code === 200) {
            this.$message.success(
              this.tool.user_collected
                ? this.$i18n.t('cancelFavoritesSuccess')
                : this.$i18n.t('addFavoritesSuccess')
            )
            this.tool.user_collected = this.tool.user_collected ? 0 : 1

            this.tool.collected_count = this.tool.user_collected
              ? parseInt(this.tool.collected_count) + 1
              : parseInt(this.tool.collected_count) - 1
          }
        } catch (error) {
          this.cLoading = false
          console.log(error)
        }
      } catch (error) {}
    },
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
  },
}
</script>
<style lang='scss' scoped>
.tool-container {
  .box {
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.06);
    border-radius: 12px;
    border: 1px solid #e5e5e5;
  }
  .tool-pic {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
  }
  .tool-name {
    font-size: 32px;
    line-height: 40px;
  }
  .t-label {
    padding: 3px 10px;
  }
  @media (min-width: 640px) {
    .sm\:min-h-11 {
      min-height: 44px;
    }
  }
}
</style>
